/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.beans.DataOwnerDecorator;
import ca.ubc.icapture.genapha.beans.DataRequestDecorator;
import ca.ubc.icapture.genapha.beans.Login;
import ca.ubc.icapture.genapha.forms.MyDataRequestForm;
import icapture.SQLMgr;
import icapture.beans.DB.DataRequest;
import icapture.beans.DB.DataRequestApproval;
import icapture.beans.DB.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author btripp
 */
public class MyDataRequestAction extends Action
{

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    {
        HttpSession session = request.getSession();
        if (Login.getLoggedIn(session))
        {
            User user = Login.getUser(session);
            if (user == null)
            {
                // User info is missing.
                // Something is broken. Relogin.
                return mapping.findForward("login");
            }

            MyDataRequestForm dataRequestListForm = (MyDataRequestForm) form;
            // Create a map linking data request (DataRequestDecorator) with its approvals(DataOwnerDecorator)
            Map<DataRequestDecorator, List<DataOwnerDecorator>> dataReqMap = new HashMap<DataRequestDecorator, List<DataOwnerDecorator>>();
            List<DataRequest> dataRequestList = SQLMgr.getDataRequests(user);
            for (DataRequest dr : dataRequestList)
            {
                List<DataOwnerDecorator> ownerList = new ArrayList<DataOwnerDecorator>();
                for (DataRequestApproval dra : SQLMgr.getDataRequestApprovals(user, dr.getRequestId()))
                {
                    ownerList.add(new DataOwnerDecorator(dra));
                }
                dataReqMap.put(new DataRequestDecorator(dr), ownerList);
            }
            dataRequestListForm.setDataReqMap(dataReqMap);
            return mapping.findForward("success");
        }
        else
        {
            return mapping.findForward("login");
        }
    }
}
